package org.goyo.main.web.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.goyo.common.baseBean.AjaxResult;
import org.goyo.common.exception.DBException;
import org.goyo.common.exception.ServiceException;
import org.goyo.common.utils.Pager;
import org.goyo.main.domain.entity.system.SysMenu;
import org.goyo.main.domain.entity.system.SysUser;
import org.goyo.main.services.comet4j.IComet4jService;
import org.goyo.main.services.log.MethodLog;
import org.goyo.main.services.system.ISysMenuService;
import org.goyo.main.services.system.ISysUserService;
import org.goyo.main.services.system.ISystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/system")
public class SystemController {
  private static Logger logger = LoggerFactory.getLogger(SystemController.class);
  @Resource
  private ISysUserService sysUserService;
  
  @Resource
  private ISystemService systemService;

  @Resource
  private ISysMenuService sysMenuService;
	
  @Resource
  private PasswordEncoder passwordEncoder;
  
  @Resource
  private IComet4jService comet4jService;

  /**
   * 跳转到登录界面
   * 
   * @return
   */
  @MethodLog("请求登录")
  @RequestMapping("/login")
  public String toLogin(HttpServletRequest request, HttpServletResponse response, Model model) {
    String error = request.getParameter("login_error");
    model.addAttribute("login_error", error);
    return "/login";
  }

  /**
   * 跳转到main界面
   * 
   * @return
   */
  @RequestMapping("/main")
  public String toMain(Model model) {
    //获得用户信息
		SysUser user = (SysUser)SessionUtil.getAttribute("user");
		try {
		  if(user.isSupper()){
		    List<SysMenu> list =  sysMenuService.findBySupper();
            model.addAttribute("list", list);
		  }else{
		    List<SysMenu> list =  sysMenuService.findByUserId(user.getUuid());
            model.addAttribute("list", list);
		  }
			
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		return "/main";
  }

  /**
   * 跳转至密码修改页面
   * 
   * @return
   */
  @RequestMapping("/toChangePassword")
  public String toChangePassword() {
    return "/system/sysChangePassword";
  }

  @MethodLog("跳转至日志页面")
  @RequestMapping("/toShowLog")
  public String toShowLog() {
    return "/system/sysShowLog";
  }
  
  @MethodLog("查询日志列表")
  @RequestMapping("/showLogList")
  @ResponseBody
  public String showLogList(HttpServletRequest request,Model model) throws Exception {
    SysUser user = (SysUser)SessionUtil.getAttribute("user");
      JSONObject data = null;
      //分页条件
      int page = Integer.parseInt(request.getParameter("page"));
      int pageSize = Integer.parseInt(request.getParameter("pagesize"));
      String sortname = request.getParameter("sortname");
      String sortorder = request.getParameter("sortorder");
      
      String where = request.getParameter("where"); 
      
      if (null != user) {
        if (null == where || where.trim().length() == 0) {
          where = " userId ='" + user.getUuid() + "'" ;
        } else {
          where += " and userId ='" + user.getUuid() + "'" ;
        }
      }
      //分页器
      Pager pager = Pager.convert(page, pageSize, sortname, sortorder);
      pager = systemService.findByCondition(where, pager);
      Map<String,Object> map = new HashMap<String,Object>();
      map.put("Rows", pager.getList());
      map.put("Total", pager.getCount());
      data = JSONObject.fromObject(map);
      return data.toString();
  }
  
  
  @MethodLog("跳转至代办事项页面")
  @RequestMapping("/toShowTaskMsg")
  public String toShowTaskMsg() {
    return "/system/sysShowTaskMsg";
  }
  
  @MethodLog("查询代办事项列表")
  @RequestMapping("/showTaskMsgList")
  @ResponseBody
  public String showTaskMsgList(HttpServletRequest request,Model model) throws Exception {
    SysUser user = (SysUser)SessionUtil.getAttribute("user");
      JSONObject data = null;
      Map<String,Object> map = new HashMap<String,Object>();
      List rows = comet4jService.getInfoList();
      map.put("Rows", rows);
      map.put("Total", rows.size());
      data = JSONObject.fromObject(map);
      return data.toString();
  }
  
  
  @RequestMapping("/changePassword")
  @ResponseBody
  public AjaxResult changePassword(HttpServletRequest request, HttpServletResponse response,
      Model model) {

    String old_pwd = passwordEncoder.encodePassword(request.getParameter("old_pwd"), null);
    String new_pwd = passwordEncoder.encodePassword(request.getParameter("new_pwd"), null);
    String new_re_pwd = passwordEncoder.encodePassword(request.getParameter("new_re_pwd"), null);
    SecurityContextImpl securityContextImpl =
        (SecurityContextImpl) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
    SysUser sysuser = null;
    try {
      sysuser = sysUserService.findByUserName(securityContextImpl.getAuthentication().getName());
      if (old_pwd.equals(sysuser.getPassword())) {
        if (new_pwd.equals(new_re_pwd)) {
          sysuser.setPassword(new_pwd);
          logger.info("修改密码成功！");
          return AjaxResult.resultSuccess("修改密码成功！", null);
          // sysUserService
        } else {
          logger.debug("修改密码失败：两次输入新密码不一致！");
          return AjaxResult.resultFail("两次输入新密码不一致！", null);
        }
      } else {
        logger.debug("修改密码失败：旧密码错误！");
        return AjaxResult.resultFail("旧密码错误！", null);
      }
    } catch (DBException e) {
      logger.error(e.getMessage(), e);
    } catch (ServiceException e) {
      logger.error(e.getMessage(), e);
    }

    // 登录密码，未加密的
    System.out.println("Credentials:" + securityContextImpl.getAuthentication().getCredentials());
    WebAuthenticationDetails details =
        (WebAuthenticationDetails) securityContextImpl.getAuthentication().getDetails();
    // 获得访问地址
    System.out.println("RemoteAddress" + details.getRemoteAddress());
    // 获得sessionid
    System.out.println("SessionId" + details.getSessionId());
    // 获得当前用户所拥有的权限
    List<GrantedAuthority> authorities =
        (List<GrantedAuthority>) securityContextImpl.getAuthentication().getAuthorities();
    for (GrantedAuthority grantedAuthority : authorities) {
      System.out.println("Authority" + grantedAuthority.getAuthority());
    }
    return null;
  }
  
  @RequestMapping("/welcome")
  public String welcome(Model model){
	  return "/system/welcome";
  }
}
